<template>
  <div id="addQuestionView">
    <h2>{{ updatePage ? "修改题目" : "创建题目" }}</h2>
    <a-button
      type="outline"
      @click="doAI"
      class="ai-generate"
      :loading="loading"
      >AI 生成题目</a-button
    >
    <span style="margin-left: 8px; color: #666; font-size: 14px">
      输入标题，帮您自动生成题目及用例~
    </span>
    <a-form :model="form" label-align="left">
      <a-form-item field="title" label="标题">
        <a-input
          v-model="form.title"
          placeholder="请输入标题"
          :maxlength="20"
        />
      </a-form-item>
      <a-form-item field="tags" label="标签">
        <a-input-tag v-model="form.tags" placeholder="请选择标签" allow-clear />
      </a-form-item>
      <a-form-item field="content" label="题目内容">
        <MdEditor :value="form.content" :handle-change="onContentChange" />
      </a-form-item>
      <a-form-item field="answer" label="答案">
        <MdEditor :value="form.answer" :handle-change="onAnswerChange" />
      </a-form-item>
      <a-form-item label="判题配置" :content-flex="false" :merge-props="false">
        <a-space direction="vertical" style="min-width: 480px">
          <a-form-item field="judgeConfig.timeLimit" label="时间限制">
            <a-input-number
              v-model="form.judgeConfig.timeLimit"
              placeholder="请输入时间限制"
              mode="button"
              :min="0"
              size="large"
            />MS
          </a-form-item>
          <a-form-item field="judgeConfig.memoryLimit" label="内存限制">
            <a-input-number
              v-model="form.judgeConfig.memoryLimit"
              placeholder="请输入内存限制"
              mode="button"
              :min="0"
              size="large"
            />B
          </a-form-item>
          <a-form-item field="judgeConfig.stackLimit" label="堆栈限制">
            <a-input-number
              v-model="form.judgeConfig.stackLimit"
              placeholder="请输入堆栈限制"
              mode="button"
              :min="0"
              size="large"
            />B
          </a-form-item>
        </a-space>
      </a-form-item>
      <a-form-item
        label="测试用例配置"
        :content-flex="false"
        :merge-props="false"
      >
        <div class="test-case-container">
          <a-form-item
            v-for="(judgeCaseItem, index) of form.judgeCase"
            :key="index"
            no-style
          >
            <div class="test-case-group">
              <div direction="vertical" style="min-width: 640px">
                <a-form-item
                  :field="`form.judgeCase[${index}].input`"
                  :label="`输入用例-${index}`"
                  :key="index"
                >
                  <a-input
                    v-model="judgeCaseItem.input"
                    placeholder="请输入测试输入用例"
                  />
                </a-form-item>
                <a-form-item
                  :field="`form.judgeCase[${index}].output`"
                  :label="`输出用例-${index}`"
                  :key="index"
                >
                  <a-input
                    v-model="judgeCaseItem.output"
                    placeholder="请输入测试输出用例"
                  />
                </a-form-item>

                <a-button status="danger" @click="handleDelete(index)">
                  删除
                </a-button>
              </div>
            </div>
          </a-form-item>
        </div>
        <div style="margin-top: 32px">
          <a-button @click="handleAdd" type="outline" status="success"
            >新增测试用例
          </a-button>
        </div>
      </a-form-item>
      <div style="margin-top: 16px" />
      <!-- 提交按钮包裹容器 -->
      <div class="submit-button-container">
        <a-form-item>
          <a-button type="primary" style="min-width: 200px" @click="doSubmit">
            提交
          </a-button>
        </a-form-item>
      </div>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import MdEditor from "@/components/MdEditor.vue";
import { QuestionControllerService } from "../../../generatedQue";
import message from "@arco-design/web-vue/es/message";
import { useRoute } from "vue-router";
const loading = ref(false);
const route = useRoute();
// 如果页面地址包含 update，视为更新页面
const updatePage = route.path.includes("update");

let form = ref({
  title: "",
  tags: [],
  answer: "",
  content: "",
  judgeConfig: {
    memoryLimit: 1000,
    stackLimit: 1000,
    timeLimit: 1000,
  },
  judgeCase: [
    {
      input: "",
      output: "",
    },
  ],
});

/**
 * 根据题目 id 获取老的数据
 */
const loadData = async () => {
  const id = route.query.id;
  if (!id) {
    return;
  }
  const res = await QuestionControllerService.getQuestionByIdUsingGet(
    "",
    id as any
  );
  if (res.code === 0) {
    form.value = res.data as any;
    // json 转 js 对象
    if (!form.value.judgeCase) {
      form.value.judgeCase = [
        {
          input: "",
          output: "",
        },
      ];
    } else {
      form.value.judgeCase = JSON.parse(form.value.judgeCase as any);
    }
    if (!form.value.judgeConfig) {
      form.value.judgeConfig = {
        memoryLimit: 1000,
        stackLimit: 1000,
        timeLimit: 1000,
      };
    } else {
      form.value.judgeConfig = JSON.parse(form.value.judgeConfig as any);
    }
    if (!form.value.tags) {
      form.value.tags = [];
    } else {
      form.value.tags = JSON.parse(form.value.tags as any);
    }
  } else {
    message.error("加载失败，" + res.message);
  }
};

onMounted(() => {
  loadData();
});

const doSubmit = async () => {
  console.log(form.value);
  // 区分更新还是创建
  if (updatePage) {
    const res = await QuestionControllerService.updateQuestionUsingPost(
      form.value
    );
    if (res.code === 0) {
      message.success("更新成功");
    } else {
      message.error("更新失败，" + res.message);
    }
  } else {
    const res = await QuestionControllerService.addQuestionUsingPost(
      "",
      form.value
    );
    if (res.code === 0) {
      message.success("创建成功");
    } else {
      message.error("创建失败，" + res.message);
    }
  }
};

/**
 * 新增判题用例
 */
const handleAdd = () => {
  form.value.judgeCase.push({
    input: "",
    output: "",
  });
};

/**
 * 删除判题用例
 */
const handleDelete = (index: number) => {
  if (form.value.judgeCase.length === 1) {
    message.warning("至少要有一个测试用例");
    return;
  }
  form.value.judgeCase.splice(index, 1);
};

const onContentChange = (value: string) => {
  form.value.content = value;
};

const onAnswerChange = (value: string) => {
  form.value.answer = value;
};

const doAI = async () => {
  loading.value = true;
  const res = await QuestionControllerService.getQuestionByAiUsingPost({
    title: form.value.title,
  });
  if (res.code === 0) {
    console.log(res.data);
    form.value = res.data;
    form.value.judgeConfig.memoryLimit = Number(
      res.data.judgeConfig.memoryLimit
    );
    form.value.judgeConfig.stackLimit = Number(res.data.judgeConfig.stackLimit);
    form.value.judgeConfig.timeLimit = Number(res.data.judgeConfig.timeLimit);
    message.success("AI 生成题目成功");
    loading.value = false;
  } else {
    message.error("AI 生成题目失败，" + res.message);
  }
};
</script>

<style scoped>
#addQuestionView {
  max-width: 1200px;
  margin: 0 auto;
  padding: 32px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
}
.header {
  display: flex;
  align-items: center;
  margin-bottom: 16px; /* 调整与下方内容的间距 */
}
h2 {
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
  margin-bottom: 32px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f2f3f5;
}

/* 表单整体样式 */
.arco-form {
  padding: 0 24px;
}

/* 表单项间距优化 */
.arco-form-item {
  margin-bottom: 24px !important;
}

/* 输入框样式增强 */
.arco-input-wrapper,
.arco-input-tag {
  border-radius: 8px;
  border: 1px solid #e5e6eb;
  transition: all 0.2s;
}

.arco-input-wrapper:hover,
.arco-input-tag:hover {
  border-color: #165dff;
}

/* 数字输入框单位样式 */
.arco-input-number-suffix {
  margin-left: 8px;
  color: #86909c;
}

/* 标签样式 */
.arco-form-item-label {
  font-weight: 500;
  color: #4e5969;
}

/* 编辑器容器 */
.markdown-editor {
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  overflow: hidden;
  transition: border-color 0.2s;
}

.markdown-editor:hover {
  border-color: #165dff;
}

/* 测试用例区域样式 */
.test-case-container {
  border: 1px solid #f2f3f5;
  border-radius: 8px;
  padding: 16px;
  margin-top: 16px;
}

/* 删除按钮样式 */
.arco-btn-status-danger {
  margin-top: 8px;
  background-color: #fff2f0;
  color: #f53f3f;
  border-color: #ffcfcb;
}

/* 新增按钮样式 */
.arco-btn-status-success {
  border-color: #00b42a;
  color: #00b42a;
}

/* 提交按钮容器 */
.submit-button-container {
  text-align: center;
  margin-top: 40px;
}

/* 提交按钮样式 */
.arco-btn-primary {
  width: 200px;
  height: 40px;
  font-size: 16px;
  border-radius: 8px;
  background: linear-gradient(135deg, #165dff 0%, #1d39c4 100%);
  transition: all 0.2s;
}

.arco-btn-primary:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

/* 响应式调整 */
@media (max-width: 768px) {
  #addQuestionView {
    padding: 24px 16px;
    margin: 0 16px;
  }

  .arco-form {
    padding: 0;
  }

  .arco-input-wrapper,
  .arco-input-tag {
    width: 100% !important;
  }
}
.header {
  display: flex;
  align-items: center;
}

/* 判题配置数字输入框容器 */
.judge-config-number {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 测试用例输入框组 */
.test-case-group {
  position: relative;
  padding: 16px;
  background: #f7f8fa;
  border-radius: 8px;
  margin-bottom: 16px;
}

.test-case-group:last-child {
  margin-bottom: 0;
}

/* 操作按钮容器 */
.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 16px;
}
.ai-generate {
  margin-right: 10px;
  margin-bottom: 16px;
}
</style>
